import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class UpgradeService extends BaseService<any> {
  private readonly logger = new Logger(UpgradeService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * upgradePreCheck
   * 对应 PHP: UpgradeService_admin::upgradePreCheck()
   * 逻辑类型: undefined - undefined
   */
  async upgradePreCheck(addon: string) {
    // 基于PHP真实逻辑: upgradePreCheck
    // PHP原文: $niucloud_dir = $this->root_path . 'niucloud' . DIRECTORY_SEPARATOR;         $upgrade_dir = $this->root_path . 'upgrade' . DIRECTORY_SEPARATOR;       ...
const niucloud_dir = this.root_path  + 'niucloud' . DIRECTORY_SEPARATOR;
        const upgrade_dir = this.root_path  + 'upgrade' . DIRECTORY_SEPARATOR;
        const admin_dir = this.root_path  + 'admin' . DIRECTORY_SEPARATOR;
        const web_dir = this.root_path  + 'web' . DIRECTORY_SEPARATOR;
        const wap_dir = this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR;

        if (!is_dir(admin_dir)) throw new BusinessException('ADMIN_DIR_NOT_EXIST');
        if (!is_dir(web_dir)) throw new BusinessException('WEB_DIR_NOT_EXIST');
        if (!is_dir(wap_dir)) throw new BusinessException('UNIAPP_DIR_NOT_EXIST'];

        const data = [
            // 目录检测
            dir: [
                // 要求可读权限
                is_readable: [],
                // 要求可写权限
                is_write: []
            ]
        ];

        data[ 'dir' ][ 'is_readable' ][) = [ dir: str_replace(project_path(), '', niucloud_dir), status: is_readable(niucloud_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', upgrade_dir), status: is_readable(upgrade_dir) ];

        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', admin_dir), status: is_readable(admin_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', web_dir), status: is_readable(web_dir) ];
        data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', wap_dir), status: is_readable(wap_dir) ];

        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', niucloud_dir), status: is_write(niucloud_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', upgrade_dir), status: is_write(upgrade_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', admin_dir), status: is_write(admin_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', web_dir), status: is_write(web_dir) ];
        data[ 'dir' ][ 'is_write' ][] = [ dir: str_replace(project_path(), '', wap_dir), status: is_write(wap_dir) ];

        // 检测全部目录及文件是否可读可写，忽略指定目录

        // 忽略指定目录，admin
        const exclude_admin_dir = [ 'dist', 'node_modules', '.git' ];
        const check_res = checkDirPermissions(project_path()  + 'admin', [], exclude_admin_dir];

        // 忽略指定目录，uni-app
        const exclude_uniapp_dir = [ 'dist', 'node_modules', '.git' ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'uni-app', [], exclude_uniapp_dir)];

        // 忽略指定目录，web
        const exclude_web_dir = [ '.nuxt', '.output', 'dist', 'node_modules', '.git' ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'web', [], exclude_web_dir)];

        // 忽略指定目录，niucloud
        const exclude_niucloud_dir = [
            'public' . DIRECTORY_SEPARATOR  + 'admin',
            'public' . DIRECTORY_SEPARATOR  + 'wap',
            'public' . DIRECTORY_SEPARATOR  + 'web',
            'public' . DIRECTORY_SEPARATOR  + 'upload',
            'public' . DIRECTORY_SEPARATOR  + 'file',
            'runtime',
            'vendor',
            '.user.ini',
            '.git'
        ];
        const check_res = array_merge2(check_res, checkDirPermissions(project_path()  + 'niucloud', [], exclude_niucloud_dir)];

        if (!!check_res[ 'unreadable' ))) {
            foreach (check_res[ 'unreadable' ) as item) {
                data[ 'dir' ][ 'is_readable' ][] = [ dir: str_replace(project_path(), '', item), status: false ];
            }
  }

  /**
   * upgrade
   * 对应 PHP: UpgradeService_admin::upgrade()
   * 逻辑类型: undefined - undefined
   */
  async upgrade(addon: any[], data: any[]) {
    // 基于PHP真实逻辑: upgrade
    // PHP原文: if ($this->upgrade_task) throw new CommonException('UPGRADE_TASK_EXIST');          $upgrade_content = $this->getUpgradeContent($addon);         if (em...
if (this.upgrade_task) throw new BusinessException('UPGRADE_TASK_EXIST'];

        const upgrade_content = this.getUpgradeContent(addon);
        if (!upgrade_content.content)) throw new BusinessException("NOT_EXIST_UPGRADE_CONTENT");

        // 过滤掉没有更新版本的插件
        upgrade_content.content = array_values(array_filter(array_map(function (item){
            if (!!item.version_list)) return item;
  }

  /**
   * execute
   * 对应 PHP: UpgradeService_admin::execute()
   * 逻辑类型: undefined - undefined
   */
  async execute() {
    // 基于PHP真实逻辑: execute
    // PHP原文: if (!$this->upgrade_task) return true;          $steps = isset($this->upgrade_task[ 'steps' ]) ? array_keys($this->upgrade_task[ 'steps' ]) : array_ke...
if (!this.upgrade_task) return true;

        const steps = typeof this.upgrade_task[ 'steps' )) ? array_keys(this.upgrade_task[ 'steps' )) : any[]_keys(this.steps);
        if (typeof this.upgrade_task[ 'steps' ))) this.steps = this.upgrade_task[ 'steps' ];
        const index = array_search(this.upgrade_task[ 'step' ), steps];
        const step = steps[ index + 1 ] || '';
        const params = this.upgrade_task[ 'params' ] || [];

        if (step) {
            try {
                const res = this.step(...params);

                if (is_[res)) {
                    this.upgrade_task[ 'params' ] = res;
                } } } else {
                    this.upgrade_task[ 'step' ] = step;
                    this.upgrade_task[ 'params' ] = [];
                    this.upgrade_task[ 'executed' ][] = step;
                    if (!!this.steps[ step )[ 'title' ))) {
                        this.upgrade_task[ 'log' ][] = this.steps[ step ][ 'title' ;
  }
                if (!in_[step, [ 'upgradeComplete', 'restoreComplete' ))) {
                    Cache.set(this.cache_key, this.upgrade_task];
                } } } else {
                    this.clearUpgradeTask(2);
                }
            } catch (CloudBuildBusinessException e) {
                if (String.prototype.indexOf.call(e.getMessage(), '队列') !== false) {
                    throw new CloudBuildBusinessException(e.getMessage()];
                }
                this.upgrade_task[ 'step' ] = step;
                this.upgrade_task[ 'error' ][] = '升级失败，失败原因：' . e.getMessage() . e.getFile() . e.getLine(];

                const fail_reason = [
                    Message: '失败原因：' . e.getMessage(),
                    File: '文件：' . e.getFile(),
                    Line: '代码行号：' . e.getLine(),
                    Trace: e.getTrace()
                ];
                this.upgradeErrorHandle(fail_reason);
            } catch (\BusinessException e) {
                this.upgrade_task[ 'step' ] = step;
                this.upgrade_task[ 'error' ][] = '升级失败，失败原因：' . e.getMessage() . e.getFile() . e.getLine(];
                const fail_reason = [
                    Message: '失败原因：' . e.getMessage(),
                    File: '文件：' . e.getFile(),
                    Line: '代码行号：' . e.getLine(),
                    Trace: e.getTrace()
                ];
                this.upgradeErrorHandle(fail_reason);
            }
            return true;
  }

  /**
   * downloadFile
   * 对应 PHP: UpgradeService_admin::downloadFile()
   * 逻辑类型: undefined - undefined
   */
  async downloadFile(app_key: number, token: number, dir: number, index: number, step: number, length: number) {
    // 基于PHP真实逻辑: downloadFile
    // PHP原文: if (!$dir) {             $dir = $this->upgrade_dir . $this->upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR . 'download' . DIRECTORY_SEPARATOR . $app_key ...
if (!dir) {
            const dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'download' . DIRECTORY_SEPARATOR . app_key . DIRECTORY_SEPARATOR;
            dir_mkdir(dir);
  }

  /**
   * backupCode
   * 对应 PHP: UpgradeService_admin::backupCode()
   * 逻辑类型: undefined - undefined
   */
  async backupCode() {
    // 基于PHP真实逻辑: backupCode
    // PHP原文: ( new BackupService() )->backupCode();         return true;     }      /**      * 备份数据库      * @return true      */     public function backupSql($ind...
( this.backupService ).backupCode(];
        return true;
    }

    /**
     * 备份数据库
     * @return true
     */
    async backupSql(index = 0)
    {
        const backup_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, key: this.upgrade_task[ 'key' )];

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const result = db.setExcludeTables(not_need_backup).backupDatabaseSegment(];
        if (db.getBackupProgress() == 100) {
            this.upgrade_task[ 'log' ][] = "数据库备份完成";
  }

  /**
   * backupSql
   * 对应 PHP: UpgradeService_admin::backupSql()
   * 逻辑类型: undefined - undefined
   */
  async backupSql(index: any) {
    // 基于PHP真实逻辑: backupSql
    // PHP原文: $backup_dir = $this->upgrade_dir . $this->upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR; ...
const backup_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
        // 创建目录
        dir_mkdir(backup_dir);

        const db = new DbBackup(backup_dir, 1024 * 1024 * 2, key: this.upgrade_task[ 'key' )];

        const prefix = config('database.connections + ' . config('database.default'))[ 'prefix' ];

        // 不需要备份的表
        const not_need_backup = [
            "{prefix}sys_schedule_log",
            "{prefix}sys_user_log",
            "{prefix}jobs",
            "{prefix}jobs_failed",
            "{prefix}sys_upgrade_records",
            "{prefix}sys_backup_records"
        ];

        const result = db.setExcludeTables(not_need_backup).backupDatabaseSegment(];
        if (db.getBackupProgress() == 100) {
            this.upgrade_task[ 'log' ][] = "数据库备份完成";
  }

  /**
   * coverCode
   * 对应 PHP: UpgradeService_admin::coverCode()
   * 逻辑类型: undefined - undefined
   */
  async coverCode(index: any, addon: any) {
    // 基于PHP真实逻辑: coverCode
    // PHP原文: $this->upgrade_task[ 'is_cover' ] = 1;         if (empty($addon)) $addon = $this->upgrade_task['upgrade_apps'][0];          $app_index = array_search(...
this.upgrade_task[ 'is_cover' ] = 1;
        if (!addon)) addon = this.upgrade_task.upgrade_apps[0];

        const app_index = array_search(addon, this.upgrade_task.upgrade_apps];

        const version_list = array_reverse(this.upgrade_task[ 'upgrade_content' ].content[app_index)[ 'version_list' )];
        const code_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'download' . DIRECTORY_SEPARATOR . addon . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;

        const version_item = version_list[ index ];
        const version_no = version_item[ 'version_no' ];

        const to_dir = addon == AddonDict.FRAMEWORK_KEY ? rtrim(this.root_path, DIRECTORY_SEPARATOR) : this.root_path  + 'niucloud' . DIRECTORY_SEPARATOR  + 'addon' . DIRECTORY_SEPARATOR . addon;

        // 获取文件变更记录
        if (file_exists(code_dir . version_no  + '.txt')) {
            const change = array_filter(explode("\n", file_get_contents(code_dir . version_no  + '.txt'))];
            foreach (change as &item) {
                list(operation, md5, file) = item = explode(' ', item);
                if (operation == '-') {
                    @unlink(to_dir . file);
                }
            }
            // 合并依赖
            this.installDepend(code_dir . version_no, array_column(change, 2)];
  }

  /**
   * installDepend
   * 对应 PHP: UpgradeService_admin::installDepend()
   * 逻辑类型: undefined - undefined
   */
  async installDepend(dir: any[], change_files: any[]) {
    // 基于PHP真实逻辑: installDepend
    // PHP原文: $addon = $this->upgrade_task[ 'upgrade' ][ 'app_key' ];         $depend_service = new CoreDependService();          if ($addon == AddonDict::FRAMEWORK...
const addon = this.upgrade_task[ 'upgrade' ][ 'app_key' ];
        const depend_service = this.coreDependService;

        if (addon == AddonDict.FRAMEWORK_KEY) {
            const composer = '/niucloud/composer.json';
            const admin_package = '/admin/package.json';
            const web_package = '/web/package.json';
            const uniapp_package = '/uni-app/package.json';
  }

  /**
   * handleUniapp
   * 对应 PHP: UpgradeService_admin::handleUniapp()
   * 逻辑类型: undefined - undefined
   */
  async handleUniapp() {
    // 基于PHP真实逻辑: handleUniapp
    // PHP原文: $key = end($this->upgrade_task['upgrade_apps']);          $code_dir = $this->upgrade_dir . $this->upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR . 'downl...
const key = end(this.upgrade_task.upgrade_apps];

        const code_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'download' . DIRECTORY_SEPARATOR . key . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;
        const exclude_files = [ '.env.development', '.env.production', 'manifest.json' ];
        dir_copy(code_dir  + 'uni-app', this.root_path  + 'uni-app', exclude_files: exclude_files);

        const addon_list = ( this.coreAddonService ).getInstallAddonList(];
        const depend_service = this.coreDependService;

        if (!!addon_list)) {

            foreach (addon_list as addon => item) {
                this.addon = addon;

                // 编译 diy-group 自定义组件代码文件
                this.compileDiyComponentsCode(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR, addon];

                // 编译 pages.json 页面路由代码文件
                this.installPageCode(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR];

                // 编译 加载插件标题语言包
                this.compileLocale(this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'src' . DIRECTORY_SEPARATOR, addon);

                // 合并插件依赖
                const addon_uniapp_package = str_replace('/', DIRECTORY_SEPARATOR, project_path()  + 'niucloud/addon/{addon}/package/uni-app-package.json"];

                if (file_exists(addon_uniapp_package)) {
                    const original = depend_service.getNpmContent('uni-app'];
                    const new = depend_service.jsonFileToArray(addon_uniapp_package);

                    foreach (new as name => value) {
                        original[ name ] = typeof original[ name )) && is_[original[ name )) ? Object.assign(original[ name ), new[ name )) : new[ name ];
                    }

                    const uniapp_package = this.root_path  + 'uni-app' . DIRECTORY_SEPARATOR  + 'package.json';
                    depend_service.writeArrayToJsonFile(original, uniapp_package);
                }
            }
  }

  /**
   * refreshMenu
   * 对应 PHP: UpgradeService_admin::refreshMenu()
   * 逻辑类型: undefined - undefined
   */
  async refreshMenu(addon: any) {
    // 基于PHP真实逻辑: refreshMenu
    // PHP原文: if (empty($addon)) $addon = $this->upgrade_task['upgrade_apps'][0];         $app_index = array_search($addon, $this->upgrade_task['upgrade_apps']);   ...
if (!addon)) addon = this.upgrade_task.upgrade_apps[0];
        const app_index = array_search(addon, this.upgrade_task.upgrade_apps);

        if (addon == AddonDict.FRAMEWORK_KEY) {
            ( this.installSystemService ).installMenu(];
  }

  /**
   * installSchedule
   * 对应 PHP: UpgradeService_admin::installSchedule()
   * 逻辑类型: undefined - undefined
   */
  async installSchedule(addon: any) {
    // 基于PHP真实逻辑: installSchedule
    // PHP原文: if (empty($addon)) $addon = $this->upgrade_task['upgrade_apps'][0];         $app_index = array_search($addon, $this->upgrade_task['upgrade_apps']);   ...
if (!addon)) addon = this.upgrade_task.upgrade_apps[0];
        const app_index = array_search(addon, this.upgrade_task.upgrade_apps);

        if (addon == AddonDict.FRAMEWORK_KEY) {
            ( this.coreScheduleInstallService ).installSystemSchedule(];
  }

  /**
   * cloudBuild
   * 对应 PHP: UpgradeService_admin::cloudBuild()
   * 逻辑类型: undefined - undefined
   */
  async cloudBuild() {
    // 基于PHP真实逻辑: cloudBuild
    // PHP原文: ( new CoreCloudBuildService() )->cloudBuild();     }      /**      * 获取云编译日志      * @return array|true      */     public function gteCloudBuildLog() ...
( this.coreCloudBuildService ).cloudBuild(];
    }

    /**
     * 获取云编译日志
     * @return array|true
     */
    async gteCloudBuildLog()
    {
        const log = ( this.coreCloudBuildService ).getBuildLog(];
        if (!log)) return true;

        foreach (log[ 'data' )[ 0 ) as item) {
            if (item[ 'code' ) == 0) {
                this.upgrade_task[ 'step' ] = 'gteCloudBuildLog';
                this.upgrade_task[ 'error' ][] = item[ 'msg' ];
                Cache.set(this.cache_key, this.upgrade_task];

                const fail_reason = [
                    Message: '失败原因 云编译错误：' . item[ 'msg' ],
                    File: '',
                    Line: '',
                    Trace: ''
                );

                ( this.coreCloudBuildService ).clearTask(];

                this.upgradeErrorHandle(fail_reason];

                return true;
            }
            if (!in_[item[ 'action' ), this.upgrade_task[ 'log' ))) {
                this.upgrade_task[ 'log' ][] = item[ 'action' ];
                Cache.set(this.cache_key, this.upgrade_task);
            }
  }

  /**
   * gteCloudBuildLog
   * 对应 PHP: UpgradeService_admin::gteCloudBuildLog()
   * 逻辑类型: undefined - undefined
   */
  async gteCloudBuildLog() {
    // 基于PHP真实逻辑: gteCloudBuildLog
    // PHP原文: $log = ( new CoreCloudBuildService() )->getBuildLog();         if (empty($log)) return true;          foreach ($log[ 'data' ][ 0 ] as $item) {        ...
const log = ( this.coreCloudBuildService ).getBuildLog(];
        if (!log)) return true;

        foreach (log[ 'data' )[ 0 ) as item) {
            if (item[ 'code' ) == 0) {
                this.upgrade_task[ 'step' ] = 'gteCloudBuildLog';
                this.upgrade_task[ 'error' ][] = item[ 'msg' ];
                Cache.set(this.cache_key, this.upgrade_task];

                const fail_reason = [
                    Message: '失败原因 云编译错误：' . item[ 'msg' ],
                    File: '',
                    Line: '',
                    Trace: ''
                );

                ( this.coreCloudBuildService ).clearTask(];

                this.upgradeErrorHandle(fail_reason];

                return true;
            }
            if (!in_[item[ 'action' ), this.upgrade_task[ 'log' ))) {
                this.upgrade_task[ 'log' ][] = item[ 'action' ];
                Cache.set(this.cache_key, this.upgrade_task);
            }
  }

  /**
   * upgradeComplete
   * 对应 PHP: UpgradeService_admin::upgradeComplete()
   * 逻辑类型: undefined - undefined
   */
  async upgradeComplete() {
    // 基于PHP真实逻辑: upgradeComplete
    // PHP原文: foreach ($this->upgrade_task['upgrade_apps'] as $addon) {             if ($addon != AddonDict::FRAMEWORK_KEY) {                 $core_addon_service = ...
foreach (this.upgrade_task.upgrade_apps as addon) {
            if (addon != AddonDict.FRAMEWORK_KEY) {
                const core_addon_service = this.coreAddonService;
                const install_data = core_addon_service.getAddonConfig(addon];
                install_data[ 'icon' ] = 'addon/' . addon  + '/icon.png';
                core_addon_service.set(install_data);
            }
  }

  /**
   * upgradeErrorHandle
   * 对应 PHP: UpgradeService_admin::upgradeErrorHandle()
   * 逻辑类型: undefined - undefined
   */
  async upgradeErrorHandle(fail_reason: any[]) {
    // 基于PHP真实逻辑: upgradeErrorHandle
    // PHP原文: $steps = [];         $steps[ $this->upgrade_task[ 'step' ] ] = [];          if (isset($this->upgrade_task[ 'is_cover' ])) {             $steps[ 'resto...
const steps = [];
        steps[ this.upgrade_task[ 'step' ] ] = [];

        if (typeof this.upgrade_task[ 'is_cover' ))) {
            steps[ 'restoreCode' ] = [ step: 'restoreCode', title: '恢复源码备份' ];
            steps[ 'restoreSql' ] = [ step: 'restoreSql', title: '恢复数据库备份' ];
  }

  /**
   * restoreCode
   * 对应 PHP: UpgradeService_admin::restoreCode()
   * 逻辑类型: undefined - undefined
   */
  async restoreCode() {
    // 基于PHP真实逻辑: restoreCode
    // PHP原文: if (!isset($this->upgrade_task['is_need_backup']) || $this->upgrade_task['is_need_backup']) {             $backup_dir = $this->upgrade_dir . $this->up...
if (!typeof this.upgrade_task.is_need_backup) || this.upgrade_task.is_need_backup) {
            const backup_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'code' . DIRECTORY_SEPARATOR;
  }

  /**
   * restoreSql
   * 对应 PHP: UpgradeService_admin::restoreSql()
   * 逻辑类型: undefined - undefined
   */
  async restoreSql(index: any) {
    // 基于PHP真实逻辑: restoreSql
    // PHP原文: if (!isset($this->upgrade_task['is_need_backup']) || $this->upgrade_task['is_need_backup']) {             $backup_dir = $this->upgrade_dir . $this->up...
if (!typeof this.upgrade_task.is_need_backup) || this.upgrade_task.is_need_backup) {
            const backup_dir = this.upgrade_dir . this.upgrade_task[ 'key' ] . DIRECTORY_SEPARATOR  + 'backup' . DIRECTORY_SEPARATOR  + 'sql' . DIRECTORY_SEPARATOR;
  }

  /**
   * restoreComplete
   * 对应 PHP: UpgradeService_admin::restoreComplete()
   * 逻辑类型: undefined - undefined
   */
  async restoreComplete() {
    // 基于PHP真实逻辑: restoreComplete
    // PHP原文: ( new UpgradeRecordsService() )->failed($this->upgrade_task[ 'key' ], $this->upgrade_task['error']);         $this->clearUpgradeTask(2);         retur...
( this.upgradeRecordsService ).failed(this.upgrade_task[ 'key' ), this.upgrade_task.error];
        this.clearUpgradeTask(2);
        return true;
    }

    /**
     * 获取升级内容
     * @param string addon
     * @return * @throws \GuzzleHttp\BusinessException\GuzzleBusinessException
     */
    async getUpgradeContent(string addon = '')
    {
        const content = [
            content: [],
            upgrade_apps: []
        ];

        const upgrade = [
            product_key: BaseNiucloudClient.PRODUCT
        ];
        const apps = [];
        if (!addon) {
            upgrade[ 'app_key' ] = AddonDict.FRAMEWORK_KEY;
            upgrade[ 'version' ] = config('version.version'];
            array_push(apps, upgrade);
  }

  /**
   * getUpgradeContent
   * 对应 PHP: UpgradeService_admin::getUpgradeContent()
   * 逻辑类型: undefined - undefined
   */
  async getUpgradeContent(addon: string) {
    // 基于PHP真实逻辑: getUpgradeContent
    // PHP原文: $content = [             'content' => [],             'upgrade_apps' => []         ];          $upgrade = [             'product_key' => BaseNiucloudC...
const content = [
            content: [],
            upgrade_apps: []
        ];

        const upgrade = [
            product_key: BaseNiucloudClient.PRODUCT
        ];
        const apps = [];
        if (!addon) {
            upgrade[ 'app_key' ] = AddonDict.FRAMEWORK_KEY;
            upgrade[ 'version' ] = config('version.version'];
            array_push(apps, upgrade);
  }

  /**
   * getUpgradeTask
   * 对应 PHP: UpgradeService_admin::getUpgradeTask()
   * 逻辑类型: undefined - undefined
   */
  async getUpgradeTask() {
    // 基于PHP真实逻辑: getUpgradeTask
    // PHP原文: return $this->upgrade_task;     }      /**      * 清除升级任务      * @return true      */     public function clearUpgradeTask(int $delayed = 0, int $is_ac...
return this.upgrade_task;
    }

    /**
     * 清除升级任务
     * @return true
     */
    async clearUpgradeTask(int delayed = 0, int is_active = 0)
    {
        // 主动取消升级
        if (is_active && this.upgrade_task && !!this.upgrade_task[ 'key' ))) {
            ( this.upgradeRecordsService ).edit([ [ 'upgrade_key', '=', this.upgrade_task[ 'key' ] ], ['status', '=', UpgradeDict.STATUS_READY ] ), [status: UpgradeDict.STATUS_CANCEL)];
  }

  /**
   * clearUpgradeTask
   * 对应 PHP: UpgradeService_admin::clearUpgradeTask()
   * 逻辑类型: undefined - undefined
   */
  async clearUpgradeTask(delayed: number, is_active: number) {
    // 基于PHP真实逻辑: clearUpgradeTask
    // PHP原文: // 主动取消升级         if ($is_active && $this->upgrade_task && !empty($this->upgrade_task[ 'key' ])) {             ( new UpgradeRecordsService() )->edit([...
// 主动取消升级
        if (is_active && this.upgrade_task && !!this.upgrade_task[ 'key' ))) {
            ( this.upgradeRecordsService ).edit([ [ 'upgrade_key', '=', this.upgrade_task[ 'key' ] ], ['status', '=', UpgradeDict.STATUS_READY ] ), [status: UpgradeDict.STATUS_CANCEL)];
  }

  /**
   * geAddonPackagePath
   * 对应 PHP: UpgradeService_admin::geAddonPackagePath()
   * 逻辑类型: undefined - undefined
   */
  async geAddonPackagePath(addon: string) {
    // 基于PHP真实逻辑: geAddonPackagePath
    // PHP原文: return root_path() . 'addon' . DIRECTORY_SEPARATOR . $addon . DIRECTORY_SEPARATOR . 'package' . DIRECTORY_SEPARATOR;     }      /**      * 用户操作      *...
return root_path()  + 'addon' . DIRECTORY_SEPARATOR . addon . DIRECTORY_SEPARATOR  + 'package' . DIRECTORY_SEPARATOR;
    }

    /**
     * 用户操作
     * @param operate
     * @return void
     */
    async operate(operate)
    {
        if (!this.upgrade_task) return true;

        switch (operate) {
            case 'local':
                this.upgrade_task[ 'step' ] = 'gteCloudBuildLog';
                Cache.set(this.cache_key, this.upgrade_task];
                break;
            case 'rollback':
                const fail_reason = [
                    Message: '失败原因：一键云编译队列任务过多',
                    File: '',
                    Line: '',
                    Trace: ''
                ];
                this.upgradeErrorHandle(fail_reason);
                break;
  }

  /**
   * operate
   * 对应 PHP: UpgradeService_admin::operate()
   * 逻辑类型: undefined - undefined
   */
  async operate(operate: any) {
    // 基于PHP真实逻辑: operate
    // PHP原文: if (!$this->upgrade_task) return true;          switch ($operate) {             case 'local':                 $this->upgrade_task[ 'step' ] = 'gteClou...
if (!this.upgrade_task) return true;

        switch (operate) {
            case 'local':
                this.upgrade_task[ 'step' ] = 'gteCloudBuildLog';
                Cache.set(this.cache_key, this.upgrade_task];
                break;
            case 'rollback':
                const fail_reason = [
                    Message: '失败原因：一键云编译队列任务过多',
                    File: '',
                    Line: '',
                    Trace: ''
                ];
                this.upgradeErrorHandle(fail_reason);
                break;
  }

  /**
   * executeSql
   * 对应 PHP: UpgradeService_admin::executeSql()
   * 逻辑类型: undefined - undefined
   */
  async executeSql(sql_file: string) {
    // 基于PHP真实逻辑: executeSql
    // PHP原文: $sql_content = file_get_contents($sql_file);          if (!empty($sql_content)) {             $prefix = config('database.connections.mysql.prefix');  ...
const sql_content = file_get_contents(sql_file);

        if (!!sql_content)) {
            const prefix = config('database.connections.mysql.prefix');
            const sql_data = array_filter(this.getSqlQuery(sql_content)];

            if (!!sql_data)) {
                foreach (sql_data as sql) {
                    const sql = prefix ? this.handleSqlPrefix(sql, prefix) : sql;
                    Db.query(sql);
                }
            }
  }
}
